package com.leetcode.problems067;

/**
 * https://leetcode-cn.com/problems/add-binary/
 * @Date 2021/12/09 14:34
 * @Author ghery
 * @Version V1.0
 */
public class Solution {

    public String addBinary(String a, String b) {
        int i = a.length() - 1;
        int j = b.length() - 1;
        StringBuilder res = new StringBuilder();
        int carry = 0;
        while(i >= 0 && j >= 0){
            int c1 = a.charAt(i) - '0';
            int c2 = b.charAt(j)- '0';
            if((c1 + c2 + carry) / 2 == 1){
                res.insert(0,(c1 + c2 + carry) % 2);
                carry = 1;
            }else{
                res.insert(0,(c1 + c2 + carry));
                carry = 0;
            }
            i--;
            j--;
        }
        int k = i > j ? i:j;
        String str = i > j ? a : b;
        while(k >= 0){
            int c1 = str.charAt(k) - '0';
            if((c1 + carry) / 2 == 1){
                res.insert(0,(c1 + carry) % 2);
                carry = 1;
            }else{
                res.insert(0,(c1 + carry));
                carry = 0;
            }
            k--;
        }
        if(carry != 0){
            res.insert(0,carry);
        }
        return res.toString();
    }

    public static void main(String[] args) {
        String a = "1010";
        String b = "1011";
        String  res = new Solution().addBinary(a,b);
        System.out.println(res);
    }
}
